package api

import (
	"blogdemo/gin/errmsg"
	"blogdemo/gin/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func UpdateProfile(c *gin.Context) {
	var profile model.Profile
	_ = c.ShouldBind(&profile)
	fmt.Println(profile.Username)
	_, flag := model.GetProfile(profile.Username)
	// 个人资料是否存在
	if !flag {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": errmsg.PROFILE_NOEXIST,
			"data":   profile,
			"msg":    errmsg.GetErrMsg(errmsg.PROFILE_NOEXIST),
		})
		fmt.Println("个人资料不存在")
		c.Abort()
		return
	}

	// 昵称是否为空
	if !model.CheckNickname(profile.Nickname) {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": errmsg.NICKNAME_EMPTY,
			"data":   profile,
			"msg":    errmsg.GetErrMsg(errmsg.NICKNAME_EMPTY),
		})
		fmt.Println("昵称为空")
		c.Abort()
		return
	}

	// 更新个人资料
	msgCode := model.ChangeProfile(&profile)
	if msgCode == errmsg.FAIL {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": errmsg.FAIL,
			"data":   profile,
			"msg":    errmsg.GetErrMsg(errmsg.FAIL),
		})
		fmt.Println("个人资料更新失败")
		c.Abort()
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status": errmsg.SUCCESS,
		"data":   profile,
		"msg":    errmsg.GetErrMsg(errmsg.SUCCESS),
	})
	fmt.Println("个人资料更新成功")
}
